#include "preHeader.h"
#include "MapTeam.h"
#include "Map/MapInstance.h"

MapTeam::MapTeam(MapInstance* pMapInstance, uint16 gsId, uint32 teamId)
: m_pMapInstance(pMapInstance)
, m_gsId(gsId)
, m_teamId(teamId)
, m_teamLeader(ObjGUID_NULL)
{
}

MapTeam::~MapTeam()
{
	for (auto itr = m_inMapTeamMemebers.begin(); itr != m_inMapTeamMemebers.end();) {
		itr++->second->SetTeam(NULL);
	}
}

void MapTeam::LoadTeamFromGSPacket(INetPacket& pack)
{
	uint64 teamLeader = pack.Read<uint64>();
	m_teamLeader = GetGuidFromValue(m_gsId, teamLeader);
	DBGASSERT(teamLeader != 0);
	pack >> m_teamName;

	uint16 memberCount = pack.Read<uint16>();
	DBGASSERT(memberCount > 0 && memberCount <= MAX_TEAM_MEMBER);

	m_allTeamMembers.clear();
	for (uint16 i = 0; i < memberCount; ++i) {
		auto teamMember = GetGuidFromValue(m_gsId, pack.Read<uint64>());
		m_allTeamMembers.insert(teamMember);
		auto pPlayer = m_pMapInstance->GetAvailablePlayer(teamMember);
		if (pPlayer != NULL) {
			pPlayer->SetTeam(this);
		}
	}

	for (auto itr = m_inMapTeamMemebers.begin(); itr != m_inMapTeamMemebers.end();) {
		auto pPlayer = itr++->second;
		if (m_allTeamMembers.count(pPlayer->GetGuid()) == 0) {
			pPlayer->SetTeam(NULL);
		}
	}
}

void MapTeam::AddPlayer(Player* pPlayer)
{
	DBGASSERT(m_allTeamMembers.count(pPlayer->GetGuid()) != 0);
	m_inMapTeamMemebers[pPlayer->GetGuid()] = pPlayer;
}

void MapTeam::RemovePlayer(Player* pPlayer)
{
	DBGASSERT(m_allTeamMembers.count(pPlayer->GetGuid()) != 0);
	m_inMapTeamMemebers.erase(pPlayer->GetGuid());
}

void MapTeam::ChangeLeader(ObjGUID playerGuid, const std::string& playerName)
{
	DBGASSERT(m_allTeamMembers.count(playerGuid) != 0);
	m_teamLeader = playerGuid;
	m_teamName = playerName;
}
